package com.hm.common.api;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.hm.common.utils.DateUtils;
import com.hm.common.utils.JSONUtils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * 
 * @author hwg
 *
 *         2020年12月18日
 */
@ApiModel(description = "通用响应返回对象")
public class ApiResult<T> implements Serializable {
	@ApiModelProperty("请求标识")
	private String requestId;
	@ApiModelProperty("状态码，只有200为成功，其他均为异常情况")
	private int status;
	@ApiModelProperty("提示信息")
	private String message;
	@ApiModelProperty("访问路径")
	private String path;
	@ApiModelProperty("返回的数据，不需要返回数据时，此属性返回为null")
	private T data;
	@ApiModelProperty("时间戳，用于校验时间的场所")
	private String timestamp;

	public ApiResult(String requestId, int status, String message, String path, T data) {
		this.requestId = requestId;
		this.status = status;
		this.message = message;
		this.path = path;
		this.data = data;
		this.timestamp = DateUtils.fnow();
	}

	public static <T> ApiResult<T> of(String requestId, int status, String message, String path, T data) {
		return new ApiResult<T>(requestId, status, message, path, data);
	}

	public static <T> ApiResult<T> of(String requestId, ApiStatus status, String message, String path, T data) {
		return of(requestId, status.getStatus(), message, path, data);
	}

	public static <T> ApiResult<T> of(String requestId, ApiStatus status, String path) {
		return of(requestId, status.getStatus(), status.getMsg(), path, null);
	}

	public static <T> ApiResult<T> of(String requestId, String path) {
		return of(requestId, ApiStatus.STATUS_200, path);
	}

	public Map<String, Object> toMap() {
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("requestId", requestId);
		m.put("status", status);
		m.put("message", message);
		m.put("path", path);
		if (data != null) {
			m.put("data", data);
		}
		m.put("timestamp", timestamp);
		return m;
	}
	
	public String toJson() throws JsonProcessingException {
		return JSONUtils.toJson(toMap());
	}

	public String getRequestId() {
		return requestId;
	}

	public void setRequestId(String requestId) {
		this.requestId = requestId;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

}
